package com.louis.web.tag;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.louis.util.MethodUtil;
import com.louis.util.StringUtil;

/**
 * <p>
 * BeanValueTag
 * </p>
 * 
 * @author: louisjiang
 * @version: 1.0.0,Apr 26, 201212:31:36 PM
 */

public class BeanTag extends AbstractTag {

	/**
	 * longBeanValueTag.javaserialVersionUID
	 */
	private static final long	serialVersionUID	= -164823638162476409L;

	private String				bean;
	private String				field;
	private String				var;
	private String				scope				= "request";

	/**
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @see com.louis.web.tag.AbstractTag#doStartTagInternal()
	 */
	@Override
	public int doStartTagInternal() throws Exception {
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.pageContext.getServletContext());
		Object beanObject = wac.getBean(bean);
		if (StringUtil.hasText(field)) {
			Method getterMethod = MethodUtil.getGetterMethod(beanObject.getClass(), field);
			if (getterMethod != null) {
				beanObject = getterMethod.invoke(beanObject);
			}
		}
		outprint(beanObject);
		return EVAL_BODY_INCLUDE;
	}

	/**
	 * <method description>
	 * 
	 * @param object
	 * @throws IOException
	 */

	private void outprint(Object object) throws IOException {
		if (object != null) {
			if (StringUtil.hasText(var)) {
				if (scope.equalsIgnoreCase("session")) {
					getSession().setAttribute(var, object);
				} else if (scope.equalsIgnoreCase("request")) {
					getRequest().setAttribute(var, object);
				}
			} else {
				this.pageContext.getOut().write(object.toString());
			}
		}
	}

	/**
	 * @return the bean
	 */
	public String getBean() {
		return this.bean;
	}

	/**
	 * @param bean
	 *            the bean to set
	 */
	public void setBean(String bean) {
		this.bean = bean;
	}

	/**
	 * @return the field
	 */
	public String getField() {
		return this.field;
	}

	/**
	 * @param field
	 *            the field to set
	 */
	public void setField(String field) {
		this.field = field;
	}

	/**
	 * @return the var
	 */
	public String getVar() {
		return this.var;
	}

	/**
	 * @param var
	 *            the var to set
	 */
	public void setVar(String var) {
		this.var = var;
	}

	/**
	 * @return the scope
	 */
	public String getScope() {
		return this.scope;
	}

	/**
	 * @param scope
	 *            the scope to set
	 */
	public void setScope(String scope) {
		this.scope = scope;
	}
}
